<template>
    <el-tabs v-model="activeName" type="card" class="demo-tabs"  tab-position="" @tab-click="handleClick">
        <el-tab-pane name="1">
            <template #label>
                <span class="tab-label">开仓</span>
            </template>
            <div class="content">
                <div class="content-item-top">
                    <el-tabs
                        v-model="activeName_sub_1"
                        class="demo-tabs-1"
                        @tab-click="handleClick"
                    >
                        <el-tab-pane label="市价" name="1">

                            <!-- 可用余额 -->
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="除去订单和仓位保证金后的余额"
                                    placement="top"
                                >
                                    可用余额:
                                </el-tooltip>
                                &nbsp;<span>{{ account.available }}</span></p>
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="开仓所需的初始保证金"
                                    placement="top"
                                >
                                    仓位保证金:
                                </el-tooltip>
                                &nbsp;<span>{{ account.position_initial_margin }}</span></p>
                            <!-- 输入开仓数量 -->
                            <div class="order-item-size">
                                <div class="label-text">
                                    <span class="label">合约数量:</span>
                                    <el-input-number v-model="creatOrderOperation.size" :min="0" :step="1" :max="100" @change="handleChange" />
                                </div>
                            </div>
                            <div class="order-item-price">
                                <div class="label-text">
                                     <p class="text">开仓价格:</p>
                                </div>
                                <div class="label-text-btn">
                                    市价
                                </div>
                            </div>
                            <div class="order-item-price">
                                <div class="label-text">
                                    <p class="text">
                                        <el-tooltip
                                            class="box-item"
                                            effect="dark"
                                            content="市价单当前只支持 ioc 模式"
                                            placement="top"
                                        >
                                            策略选择:&nbsp;&nbsp;ioc
                                        </el-tooltip>
                                    </p>
                                </div>
                            </div>

                            <div class="order-item-oprater">
                                <div class="label-text">
                                     <p class="text">开仓操作:</p>
                                </div>
                                <div class="item">
                                    <div class="btn green" @click="openPosition(1,'t-kaiduo-shijia',false)">
                                        <div class="center">开多</div>
                                        <div class="right">看涨</div>
                                    </div>
                                </div>
                                <div class="item">
                                    <div class="btn red">
                                        <div class="center" @click="openPosition(-1,'t-kaikong',false)">开空</div>
                                        <div class="right">看跌</div>
                                    </div>
                                </div>
                            </div>

                        </el-tab-pane>
                        <el-tab-pane label="限价" name="2">

                            <!-- 可用余额 -->
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="除去订单和仓位保证金后的余额"
                                    placement="top"
                                >
                                    可用余额:
                                </el-tooltip>
                                &nbsp;<span>{{ account.available }}</span></p>
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="开仓所需的初始保证金"
                                    placement="top"
                                >
                                    仓位保证金:
                                </el-tooltip>
                                &nbsp;<span>{{ account.position_initial_margin }}</span></p>
                            <!-- 输入开仓数量 -->
                            <div class="order-item-size">
                                <div class="label-text">
                                    <span class="label">合约数量:</span>
                                    <el-input-number v-model="creatOrderOperation.size" :min="0" :step="1" :max="100" @change="handleChange" />
                                </div>
                            </div>

                            <div class="order-item-price">
                                <div class="label-text">
                                    <p class="text">开仓价格(限价):</p>
                                </div>
                                <el-input
                                        v-model="creatOrderOperation.price"
                                        size="large"
                                        style="text-align: center;"
                                        placeholder="请输入开仓价格"
                                >
                                <template #prepend>价格(USDT)</template>
                                </el-input>
                            </div>
                            <div class="order-item-price">
                                <div class="label-text">
                                    <p class="text">开仓策略(限价):</p>
                                </div>
                                <el-select v-model="creatOrderOperation.tif" placeholder="请选择策略" size="large" style="width: 320px;">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                                </el-select>
                            </div>

                            <div class="order-item-oprater">
                                <div class="label-text">
                                    <p class="text">开仓操作:</p>
                                </div>
                                <div class="item">
                                    <div class="btn green" @click="openPosition(1,'t-kaiduo-xianjia',true)">
                                        <div class="center">开多</div>
                                        <div class="right">看涨</div>
                                    </div>
                                </div>
                                <div class="item">
                                    <div class="btn red">
                                        <div class="center" @click="openPosition(-1,'t-kaikong-xianjia',true)">开空</div>
                                        <div class="right">看跌</div>
                                    </div>
                                </div>
                            </div>

                        </el-tab-pane>
                        
                    </el-tabs>
                </div>
            </div>
        </el-tab-pane>
        <el-tab-pane name="2">
            <template #label>
                <span class="tab-label">平仓</span>
            </template>
            <div class="content">
                <div class="content-item-top">
                    <el-tabs
                        v-model="activeName_sub_1"
                        class="demo-tabs-1"
                        @tab-click="handleClick"
                    >
                        <el-tab-pane label="市价" name="1">

                            <!-- 可用余额 -->
                            <p class="text">可用余额:&nbsp;<span>{{ account.available }}</span></p>
                            <!-- 输入开仓数量 -->
                            <div class="order-item-size">
                                <div class="label-text">
                                    <span class="label">合约数量:</span>
                                    <el-input-number v-model="creatOrderOperation.size" :disabled="true" :min="0" :step="1" :max="100" @change="handleChange" />
                                </div>
                                
                            </div>
                            <div class="order-item-price">
                                <div class="label-text">
                                     <p class="text">平仓价格:</p>
                                </div>
                                <div class="label-text-btn">
                                    市价
                                </div>
                            </div>

                            <div class="order-item-oprater">
                                <div class="label-text">
                                     <p class="text">平仓操作(单仓模式):</p>
                                </div>
                                <div class="item" @click="closePosition(1,'t-pingcang-shijia',false)">
                                    <div class="btn green">
                                        <div class="center">平仓</div>
                                    </div>
                                </div>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="限价" name="2">

                            <!-- 可用余额 -->
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="除去订单和仓位保证金后的余额"
                                    placement="top"
                                >
                                    可用余额:
                                </el-tooltip>
                                &nbsp;<span>{{ account.available }}</span></p>
                            <p class="text">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="开仓所需的初始保证金"
                                    placement="top"
                                >
                                    仓位保证金:
                                </el-tooltip>
                                &nbsp;<span>{{ account.position_initial_margin }}</span></p>
                            <!-- 输入开仓数量 -->
                            <div class="order-item-size">
                                <div class="label-text">
                                    <span class="label">合约数量:</span>
                                    <el-input-number :disabled="true" v-model="creatOrderOperation.size" :min="0" :step="1" :max="100" @change="handleChange" />
                                </div>
                            </div>

                            <div class="order-item-price">
                                <div class="label-text">
                                    <p class="text">平仓价格(限价):</p>
                                </div>
                                <el-input
                                        v-model="creatOrderOperation.price"
                                        size="large"
                                        style="text-align: center;"
                                        placeholder="请输入开仓价格"
                                >
                                <template #prepend>价格(USDT)</template>
                                </el-input>
                            </div>
                            <div class="order-item-price">
                                <div class="label-text">
                                    <p class="text">平仓策略(限价):</p>
                                </div>
                                <el-select v-model="creatOrderOperation.tif" placeholder="请选择策略" size="large" style="width: 320px;">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                                </el-select>
                            </div>

                            <div class="order-item-oprater">
                                <div class="label-text">
                                    <p class="text">开仓操作(单仓模式):</p>
                                </div>
                                <div class="item">
                                    <div class="btn green" @click="closePosition(1,'t-pingcang-xianjia',true)">
                                        <div class="center">平仓</div>
                                    </div>
                                </div>
                            </div>

                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </el-tab-pane>
    </el-tabs>
    <!-- 交易信息 -->
    <div class="order-info">
        <el-tabs v-model="activeName_sub_1_1" class="demo-tabs" @tab-click="handleClick">
            <!-- <el-tab-pane label="当前委托(0)" name="1">User</el-tab-pane> -->
            <el-tab-pane :label="'持有仓位('+PositionsInfo.length+')'" name="1">
                <div class="infocard" v-for="(item, index) in PositionsInfo">
                    <div class="order">
                        <span>方向:</span>
                        <br>
                        <span>{{PositionsInfo[index].size>0?'开多':'开空' }}</span>
                    </div>
                    <div class="order">
                        <span>开仓价格:</span>
                        <br>
                        <span>{{ PositionsInfo[index].entry_price }}</span>
                    </div>
                    <div class="order">
                        <span>标记价格:</span>
                        <br>
                        <span v-if="symbol" style="color: #FC4100;">↑{{ tradeInfo.mark_price }}</span>
                        <span v-else style="color: #7ABA78;">↓{{ tradeInfo.mark_price }}</span>
                    </div>
                    <div class="order">
                        <span>数量:</span>
                        <br>
                        <span>{{ PositionsInfo[index].size }}</span>
                    </div>

                    <div class="order">
                        <div class="detail" >详情</div>
                    </div>
                </div>
                
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script setup>
import { ref ,defineProps,onMounted,defineExpose,watch,inject} from 'vue'
import { getAccountPositions,createOrderv2,getFuturesAccountBalances } from '../../../api/apis'
import { ElMessage } from 'element-plus'

let activeName = ref('1')
let activeName_sub_1 = ref('1')
let activeName_sub_1_1 = ref('1')

const handleClick = (tab, event) => {
// console.log(tab, event)
}
const tradeInfo = inject('tradeInfo');


const props = defineProps({
    acountInfo: {
        type: Object,
        default: () => {},
    },
    key: {
        type: Number,
        default: () => {},
    },
    mark_price: {
        type: String,
        default: false,
    },
    CaptainParams: {
        type: Object,
        default: () => {},
    },
});

// 开仓操作
const creatOrderOperation = ref({
    size: 0,
    text: '',
    price: 0,
    tif: 'ioc',
})

// 开仓策略
const options = [
  {
    value: 'gtc',
    label: 'gtc-一直有效，直到取消',
  },
  {
    value: 'ioc',
    label: 'ioc-立即成交或者取消，只吃单不挂单',
  },
  {
    value: 'poc',
    label: 'poc-被动委托，只挂单不吃单',
  },
  {
    value: 'fok',
    label: 'fok-完全成交，或者完全取消',
  }
]


watch(() => props.key, (newValue, oldValue) => {
    getAccountPositionsfn()
})
const mark_price = ref(props.mark_price);
const symbol = ref(false); // true 代表涨，false 代表跌
const lastPrice = ref(null); // 存储上一次价格

watch(() => tradeInfo.value.mark_price, (newVal, oldVal) => {
    if (lastPrice.value !== null) { // 确保不是第一次赋值
        symbol.value = newVal > lastPrice.value; // 如果新值大于旧值，则为涨
    }
    lastPrice.value = newVal; // 更新上一次价格
}, { immediate: true });


function CaptainParamsfn(){
    if (props.CaptainParams=={}) {
    }else{
        creatOrderOperation.value.price = props.CaptainParams.price?props.CaptainParams.price:0
        creatOrderOperation.value.size = props.CaptainParams.size?props.CaptainParams.size:0
        creatOrderOperation.value.tif = props.CaptainParams.tif?props.CaptainParams.tif:'ioc'
        activeName.value =  props.CaptainParams.activeName?props.CaptainParams.activeName:activeName.value
        activeName_sub_1.value = props.CaptainParams.activeName_sub_1?props.CaptainParams.activeName_sub_1:activeName_sub_1.value
        activeName_sub_1_1.value =  props.CaptainParams.activeName_sub_1_1?props.CaptainParams.activeName_sub_1_1:activeName_sub_1_1.value
    }
}


watch(() => props.CaptainParams, (newVal, oldVal) => {
    CaptainParamsfn()
}, { immediate: true });


// 获取仓位信息
const PositionsInfo = ref([])
function getAccountPositionsfn(){
    const {gate_key,gate_secret} = props.acountInfo
    getAccountPositions({
        gate_key,
        gate_secret,
        settle: 'usdt',
        holding:true,
        limit:100,
        offset:0
    }).then((res) => {
        const response = res.data
        if (response.code==200) {
            PositionsInfo.value = response.data
            } else {
            ElMessage.error(`请求失败，错误代码：${response.code}，错误信息：${response.msg}`);
            }
        })
        .catch((error) => {
            ElMessage.error('请求发生错误，请检查网络或稍后再试');
            console.error('获取账户列表时出现错误:', error);
        });
}




function openPosition(multiple,text,modelopetion){
    const {gate_key,gate_secret} = props.acountInfo
    let {size,price,tif} = creatOrderOperation.value
    if (!modelopetion) {
        price = 0
        tif = 'ioc'
    }
    createOrderv2({
        gate_key,
        gate_secret,
        settle: 'usdt',
        contract :"BTC_USDT",
        size:multiple*size,
        text,
        price:parseFloat(price) ,
        tif:tif,
    }).then((res) => {
        if (res.data.code==200) {
            // if (modelopetion.value===1) {
            //     ElMessage.success(multiple===1?'开多成功':'开空成功')
            // }
            ElMessage.success(multiple===1?'开多成功':'开空成功')

            getAccountPositionsfn()
            getAccountBalances()
            creatOrderOperation.value = {
                size: 0,
                text: '',
                price: 0,
                tif: 'ioc',
            }
            } else {
            ElMessage.error(`请求失败，错误代码：${res.data.code}，错误信息：${res.data.msg}`);
            }
        })
    .catch((error) => {
        ElMessage.error('请求发生错误，请检查网络或稍后再试');
        console.error('获取账户列表时出现错误:', error);
    })
}
function closePosition(multiple,text,modelopetion){
    const {gate_key,gate_secret} = props.acountInfo
    let {size,price,tif} = creatOrderOperation.value
    if (!modelopetion) {
        price = 0
        tif = 'ioc'
    }

    createOrderv2({
        gate_key,
        gate_secret,
        settle: 'usdt',
        contract :"BTC_USDT",
        size:0,
        text,
        price ,
        tif,
        close:true
    }).then((res) => {
        if (res.data.code==200 ) {
            // if (modelopetion.value===1) {
            //     ElMessage.success('平仓成功')
            // }
            ElMessage.success('平仓成功')

            getAccountPositionsfn()
            getAccountBalances()
            creatOrderOperation.value = {
                size: 0,
                text: '',
                price: 0,
                tif: 'ioc',
            }
            } else {
            ElMessage.error(`请求失败，错误代码：${res.data.code}，错误信息：${res.data.msg}`);
            }
        })
    .catch((error) => {
        console.error('获取账户列表时出现错误:', error);
    })
}

// 获取账户余额
const account = ref({
    balance: 0
})


// 全部开仓逻辑开多
const allcreatOrderOperationMore = () => {
    console.log('批量开多成功',props.acountInfo.id)
    openPosition(1,'t-kaiduo',2)
    
    
};
// 全部开仓逻辑开空
const allcreatOrderOperationLose = () => {
    console.log('批量开空成功',props.acountInfo.id)
    openPosition(-1,'t-kaikong',2)
    
};
// 全部平仓
const allCloseOrderOperationLose = () => {
    console.log('批量平仓成功',props.acountInfo.id)
    closePosition(-1,'t-t-pingcang-shijia',2)
    
};

// 使用 defineExpose 公开函数
defineExpose({
    allcreatOrderOperationMore,
    allcreatOrderOperationLose,
    allCloseOrderOperationLose
});

// 获取余额
function getAccountBalances(){
    const {gate_key,gate_secret} = props.acountInfo

    getFuturesAccountBalances({
        gate_key,
        gate_secret,
        settle:'usdt',
        contract:'',
    }).then(res=>{
        if (res.data.code==200) {
            account.value = res.data.data
        } else {
        ElMessage.error(`请求失败，错误代码：${res.data.code}，错误信息：${res.data.msg}`);
        }
    }).catch(error => {
        ElMessage.error('请求发生错误，请检查网络或稍后再试');
        console.error('获取账户列表时出现错误:', error);
    });
}

// 开仓逻辑
const order = ref({
    size: 0
})


const handleChange = (value) => {
}

onMounted(() => {
    getAccountPositionsfn()
    getAccountBalances()
})


</script>
  
<style lang="scss">
.demo-tabs > .el-tabs__content {
    padding: 2px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}
.demo-tabs-1 > .el-tabs__content{
    padding: 0;
}

.demo-tabs-1{
    .text{
        font-size: 14px;
        span{
            color: #5AB2FF;
        }
    }
    .order-item-size{
        width: 100%;
    }
    .label-text{
        font-size: 18px;
        .label{
            line-height: 30px;
            margin-right: 10px;
        }
    }
    .order-item-price{
        width: 100%;
        .label-text-btn{
            background-color: #fc819ea4;
            border-radius: 8px;
            margin: 10px auto;
            text-align: center;
            font-size: 18px;
            line-height: 40px;
            color: #ffffff;
        }

    }
    .order-item-oprater{
        width: 100%;
        .item{
            .btn{
                width: 100%;
                height: 40px;
                border-radius: 8px;
                text-align: center;
                line-height: 40px;
                color: #fff;
                position: relative;
                user-select: none;
                margin: 10px auto;
                font-weight: 400;
                cursor: pointer;
                .center{
                    font-size: 18px;
                }
                .right{
                    text-align: right;
                    font-size: 14px;
                    font-weight: 400;
                    color: #fff;
                    position: absolute;
                    right: 10px;
                    top: 0px;
                }
            }
            .btn:active{
                background-color: #75A47F;
            }
            .green{
                background-color: #B5C18E;
            }
            .red{
                background-color: #FA7070;
            }
        }
    }
}
.tab-label{
    font-size: 20px;
    font-weight: 600;
    width: 100px;
    text-align: center;
    

}
.order-info{
    width: 100%;
    height: fit-content;
    .infocard{
        width: 95%;
        overflow: hidden;
        height: 40px;
        background-color: #EEF7FF;
        margin-top: 10px;
        border-radius: 8px;
        padding: 10px;
        .order{
            line-height: 20px;
            font-size: 13px;
            width: fit-content;
            text-align: center;
            float: left;
            margin: 0 10px;
            span:nth-child(1){
                color: #5AB2FF;
                width: 100%;
            }
            .detail{
                width: 30px;
                line-height: 40px;
                font-weight: 600;
                font-size: 14px;
                cursor: pointer;
                user-select: none;
            }
            .detail:hover{
                color: #98ABEE;
            }
        }
    }
}

</style>